﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.UI;
using MyWeb.Common;
using MyWeb.Datamining.SearchImage;

namespace MyWeb.TrangChinh.UC
{
    public partial class ucSearchHeader : UserControl
    {
        private readonly clsAlgorithm _algorithm = new clsAlgorithm();
        public int[,] AnalysImageToSearch;
        private List<object[]> _result = new List<object[]>();

        public List<object[]> Result
        {
            get { return _result; }
            set { _result = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void radSearchText_CheckedChanged(object sender, EventArgs e)
        {
            multiview.ActiveViewIndex = radSearchText.Checked ? 0 : 1;
        }

        protected void radSearchImage_CheckedChanged(object sender, EventArgs e)
        {
            multiview.ActiveViewIndex = radSearchImage.Checked ? 1 : 0;
        }

        protected void btnSearchImage_Click(object sender, ImageClickEventArgs e)
        {
            HttpPostedFile files = FileUpload1.PostedFile;
            string adsFile = "";
            if (FileUpload1.HasFile == false || files.ContentLength > 2000000)
            {
                WebMsgBox.Show("Ảnh không hợp lệ!");
            }
            else
            {
                string fileExt = Path.GetExtension(FileUpload1.FileName);

                if (fileExt != null &&
                    (fileExt.ToLower() == ".gif" || fileExt.ToLower() == ".png" || fileExt.ToLower() == ".bmp" ||
                     fileExt.ToLower() == ".jpeg" || fileExt.ToLower() == ".jpg"))
                {
                    try
                    {
                        adsFile = FileUpload1.FileName;
                        FileUpload1.SaveAs(Request.PhysicalApplicationPath + "/ImageSearch/" + adsFile);
                    }
                    catch
                    {
                        WebMsgBox.Show("Trùng tên hoặc chưa chọn hình!");
                    }
                }
                else
                {
                    WebMsgBox.Show("Không đúng định dạng ảnh!");
                }
            }
            AnalysImageToSearch =
                _algorithm.AnalysColor(new Bitmap(Request.PhysicalApplicationPath + "/ImageSearch/" + adsFile));
            Result = _algorithm.CompareResult(AnalysImageToSearch);
            var dt = new DataTable();
            for (int i = 0; i < Result.Count; i++)
            {
                dt.Rows[i][0] = Result[i];
            }
        }
    }
}